package pl.edu.agh.bd2.servlets;

import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashSet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import pl.edu.agh.bd2.domain.Subject;
import pl.edu.agh.bd2.domain.Topic;
import pl.edu.agh.bd2.util.HibernateDAO;

/**
 * Servlet implementation class NewTopicServlet
 */
@WebServlet("/newTopic.do")
public class NewTopicServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public NewTopicServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		HibernateDAO<Topic> dao = new HibernateDAO<Topic>();
		
		HashSet<Subject> subjects = (HashSet<Subject>)session.getAttribute("subjects");
		Subject subject = null;
		
		for(Subject s: subjects){
			if(s.getName().equals((String)session.getAttribute("selectedSubject"))){
				subject = s;
				break;
			}
		}
					
		Topic topic = new Topic(request.getParameter("topic"),new Date(), subject);
		subject.addTopic(topic);
		dao.persist(topic);		
		
		RequestDispatcher view = request.getRequestDispatcher("/subjectInfo.jsp");
		view.forward(request, response);
	}
}
